package com.qiyigu.itc.speech;

import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.TextView;

import com.qiyigu.itc.speech.R;

/**
 * Created by nidone-1 on 2018/3/14.
 */

public class SpeechDialogView {

    private Context mContext;
    private WindowManager windowManager;
    private LayoutParams layoutParams;
    private View mDialogView;
    private boolean isAdded = false;

    private TextView mTextRequest;
    private TextView mTextResponse;

    private static SpeechDialogView speechDialogView;
    private SpeechDialogView(Context context){
       this.mContext = context;
    }

    public static SpeechDialogView getInstance(Context context){
        if (speechDialogView == null){
            synchronized(SpeechDialogView.class){
                if (speechDialogView == null){
                    speechDialogView = new SpeechDialogView(context);
                }
            }
        }
        return speechDialogView;
    }

    public void initView(){
        mDialogView = LayoutInflater.from(mContext).inflate(R.layout.layout_dialog,null);
        mTextRequest = mDialogView.findViewById(R.id.textView_request);
        mTextResponse = mDialogView.findViewById(R.id.textView_response);

        windowManager = (WindowManager) mContext.getSystemService(mContext.WINDOW_SERVICE);
        /*
         * LayoutParams.TYPE_SYSTEM_ERROR：保证该悬浮窗所有View的最上层
         * LayoutParams.FLAG_NOT_FOCUSABLE:该浮动窗不会获得焦点，但可以获得拖动
         * PixelFormat.TRANSPARENT：悬浮窗透明
         */
        layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, LayoutParams.TYPE_SYSTEM_ERROR,
                LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSPARENT);
        layoutParams.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
    }

    /**
    * 显示说的话
    */
    public void setTextSpeech(String str){
        if (null != str){
            mTextRequest.setText(str);
        }
    }

    /**
     * 显示说的话
     */
    public void setTextReply(String str){
        if (null != str){
            mTextResponse.setText(str);
        }
    }


    /**
     * 打开对话框
     */
    public void openView() {
        if (!isAdded) {
            windowManager.addView(mDialogView,layoutParams);
            isAdded = true;
        }
    }

    /**
     * 关闭对话框
     */
    public void closeView() {
        if (isAdded) {
            windowManager.removeView(mDialogView);
            isAdded = false;
        }
    }


}
